﻿using System;
using Audio;
using PrimeTween;
using UnityEngine;

namespace Combat
{
    public class Rocket : MonoBehaviour
    {
        public static event Action AnyRocketExploded;
        
        [SerializeField] private float speed = 8f;
        [SerializeField] private float explodeRange = 1f;
        [SerializeField] private int damage = 3;
        
        [SerializeField] private AudioClip explosionSound;

        [SerializeField] private ParticleSystem explosionPrefab;
        [SerializeField] private GameObject crossPrefab;
        
        [SerializeField] private LayerMask playerMask;
        [SerializeField] private LayerMask enemyMask;
        
        private Collider2D[] _colliders = new Collider2D[10];

        private Vector3 _targetPosition;
        private LayerMask _targetLayerMask;
        private GameObject _cross;


        private void Update()
        {
            Vector3 targetVector = _targetPosition - transform.position;
            transform.Translate(targetVector.normalized * (Time.deltaTime * speed));

            if (targetVector.magnitude < 0.3f)
            {
                Explode();
            }
        }

        public void Launch(Vector2 targetPosition, Team team)
        {
            _targetPosition = targetPosition;
            
            _targetLayerMask = team == Team.Player ? enemyMask : playerMask;
            
            _cross = Instantiate(crossPrefab, targetPosition, Quaternion.identity);
        }

        private void Explode()
        {
            AudioPlayer.Instance.PlaySound(explosionSound);
            Destroy(_cross);
            
            Instantiate(explosionPrefab, transform.position, Quaternion.identity);
            int hitCount = Physics2D.OverlapCircleNonAlloc(transform.position, explodeRange, _colliders, _targetLayerMask);
            for (int i = 0; i < hitCount && i < _colliders.Length; i++)
            {
                if (_colliders[i].TryGetComponent(out Health health))
                {
                    health.TakeDamage(damage, (_colliders[i].transform.position - transform.position).normalized);
                }
            }
            
            enabled = false;
            GetComponent<SpriteRenderer>().enabled = false;
            AnyRocketExploded?.Invoke();
            Tween.Delay(1f, () => Destroy(gameObject));
        }
    }
}